<template>
  <div class="markdown-renderer">
    <!-- 内容展示区域 -->
    <div class="content-area" v-if="content">
      <div class="markdown-content" v-html="renderedContent"></div>
      
      <!-- 目录导航 - 已注释掉
      <div class="catalog" v-if="toc.length > 0">
        <div class="catalog-title">目录</div>
        <div class="catalog-list">
          <div 
            v-for="item in toc" 
            :key="item.id"
            :class="['catalog-item', `level-${item.level}`]"
            @click="scrollToHeading(item.id)"
          >
            {{ item.text }}
          </div>
        </div>
      </div>
      -->
    </div>
    
    <!-- 空内容提示 -->
    <div v-else class="empty-content">
      <div class="empty-icon">📝</div>
      <div class="empty-text">暂无内容</div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'MarkdownRenderer',
  props: {
    content: {
      type: String,
      default: ''
    },
    imageBaseUrl: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      // toc: [] // 目录数据 - 已注释掉
    }
  },
  computed: {
    // 渲染后的HTML内容
    renderedContent() {
      return this.processHtmlContent(this.content)
    }
  },
  watch: {
    // 监听内容变化 - 已注释掉
    /*
    content: {
      handler() {
        this.updateToc()
      },
      immediate: true
    }
    */
  },
  methods: {
    // 处理HTML内容
    processHtmlContent(html) {
      if (!html) return ''
      
      // 保存imageBaseUrl到局部变量
      const imageBaseUrl = this.imageBaseUrl || ''
      
      // 处理图片标签，支持 src 和 data-href 属性
      html = html.replace(/<img([^>]*?)>/g, (match, attributes) => {
        // 提取 src 和 data-href 属性
        const srcMatch = attributes.match(/src=["']([^"']*?)["']/)
        const dataHrefMatch = attributes.match(/data-href=["']([^"']*?)["']/)
        const altMatch = attributes.match(/alt=["']([^"']*?)["']/)
        
        let imageSrc = ''
        if (dataHrefMatch) {
          // 优先使用 data-href
          imageSrc = dataHrefMatch[1]
        } else if (srcMatch) {
          // 其次使用 src
          imageSrc = srcMatch[1]
        }
        
        // 如果图片路径不是以http开头且提供了基础URL，则添加基础URL
        if (imageSrc && !imageSrc.startsWith('http') && !imageSrc.startsWith('//') && imageBaseUrl) {
          imageSrc = imageBaseUrl + imageSrc
        }
        
        const alt = altMatch ? altMatch[1] : '图片'
        
        return `<div class="image-container"><img src="${imageSrc}" alt="${alt}" class="markdown-image" style="max-width: 100% !important; max-height: 400px !important; width: auto !important; height: auto !important; object-fit: cover !important;" /></div>`
      })
      
      // 为标题添加ID和样式类
      html = html.replace(/<h([1-6])([^>]*?)>(.*?)<\/h[1-6]>/g, (match, level, attrs, text) => {
        const headingId = `heading-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
        return `<h${level} id="${headingId}" class="heading-level-${level}"${attrs}>${text}</h${level}>`
      })
      
      // 清理空的段落标签
      html = html.replace(/<p>\s*<br\s*\/?>\s*<\/p>/g, '')
      html = html.replace(/<p>\s*<\/p>/g, '')
      
      return html
    },
    
    // 解析Markdown内容（保留原方法以防需要）
    parseMarkdown(text) {
      if (!text) return { html: '', toc: [] }
      
      let html = text
      const tocData = []
      let headingId = 0
      
      // 保存imageBaseUrl到局部变量，避免在正则回调中this上下文问题
      const imageBaseUrl = this.imageBaseUrl || ''
      
      // 处理标题
      html = html.replace(/^(#{1,6})\s+(.+)$/gm, (match, level, text) => {
        const headingLevel = level.length
        const id = `heading-${++headingId}`
        
        // 添加到目录
        tocData.push({
          id,
          text: text.trim(),
          level: headingLevel
        })
        
        return `<h${headingLevel} id="${id}" class="heading-level-${headingLevel}">${text.trim()}</h${headingLevel}>`
      })
      
      // 处理图片
      html = html.replace(/!\[([^\]]*)\]\(([^)]+)\)/g, (match, alt, src) => {
        let imageSrc = src
        // 如果图片路径不是以http开头且提供了基础URL，则添加基础URL
        if (!imageSrc.startsWith('http') && !imageSrc.startsWith('//') && imageBaseUrl) {
          imageSrc = imageBaseUrl + imageSrc
        }
        return `<div class="image-container"><img src="${imageSrc}" alt="${alt || '图片'}" class="markdown-image" style="max-width: 100% !important; max-height: 400px !important; width: auto !important; height: auto !important; object-fit: cover !important;" /></div>`
      })
      
      // 处理段落（将连续的空行分隔的文本包装成段落）
      html = html.replace(/\n\n+/g, '</p>\n<p>')
      html = '<p>' + html + '</p>'
      
      // 清理空的段落标签
      html = html.replace(/<p>\s*<\/p>/g, '')
      html = html.replace(/<p>\s*<h/g, '<h')
      html = html.replace(/<\/h[1-6]>\s*<p>/g, '</h$1>')
      
      return { html, toc: tocData }
    },
    
    // 更新目录
    updateToc() {
      const { toc: newToc } = this.parseMarkdown(this.content)
      this.toc = newToc
    },
    
    // 滚动到指定标题
    scrollToHeading(id) {
      const element = document.getElementById(id)
      if (element) {
        element.scrollIntoView({ 
          behavior: 'smooth', 
          block: 'start' 
        })
      }
    }
  }
}
</script>

<style scoped lang="scss">
.markdown-renderer {
  width: 100%;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
  line-height: 1.6;
  color: var(--el-text-color-primary, #303133);
  
  // 全局图片约束 - 最高优先级
  img {
    max-width: 100% !important;
    max-height: 400px !important;
    width: auto !important;
    height: auto !important;
    object-fit: cover !important;
  }
  
  .content-area {
    display: flex;
    gap: 24px;
    
    .markdown-content {
      flex: 1;
      min-width: 0; // 防止flex子项溢出
      
      // 标题样式
      h1, h2, h3, h4, h5, h6 {
        margin: 24px 0 16px 0;
        font-weight: 600;
        line-height: 1.4;
        color: var(--el-text-color-primary, #303133);
        scroll-margin-top: 80px; // 为锚点滚动留出空间
        
        &:first-child {
          margin-top: 0;
        }
      }
      
      h1 {
        font-size: 28px;
        border-bottom: 3px solid var(--el-border-color-light, #ebeef5);
        padding-bottom: 12px;
      }
      
      h2 {
        font-size: 24px;
        border-bottom: 2px solid var(--el-border-color-lighter, #f0f0f0);
        padding-bottom: 8px;
      }
      
      h3 {
        font-size: 20px; // 调整为比正文大但比二级标题小
        border-bottom: 1px solid var(--el-border-color-lighter, #f0f0f0);
        padding-bottom: 6px;
      }
      
      h4 {
        font-size: 18px; // 调整为与正文相同大小
      }
      
      h5, h6 {
        font-size: 14px; // 调整为比正文稍小
      }
      
      // 段落样式
      p {
        margin: 16px 0;
        line-height: 1.8;
        text-align: justify;
        color: var(--el-text-color-regular, #606266);
      }
      
      // 图片样式
      .image-container {
        margin: 20px 0;
        text-align: center;
        max-width: 100%;
        overflow: hidden; // 防止图片溢出容器
        
        .markdown-image {
          max-width: 100% !important;
          max-height: 400px !important; // 使用px单位确保在web环境中生效
          width: auto !important;
          height: auto !important;
          border-radius: 8px;
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
          transition: transform 0.3s ease, box-shadow 0.3s ease;
          object-fit: cover; // 保持图片比例
          display: block; // 确保图片正确显示
          margin: 0 auto; // 居中显示
          
          &:hover {
            transform: scale(1.02);
            box-shadow: 0 6px 20px rgba(0, 0, 0, 0.2);
          }
        }
      }
      
      // 强制约束所有图片，使用更强的选择器
      img {
        max-width: 100% !important;
        max-height: 400px !important;
        width: auto !important;
        height: auto !important;
        object-fit: cover !important;
      }
    }
    
    // 目录样式
    .catalog {
      width: 280px;
      flex-shrink: 0;
      position: sticky;
      top: 20px;
      max-height: calc(100vh - 40px);
      overflow-y: auto;
      
      .catalog-title {
        font-size: 16px;
        font-weight: 600;
        color: var(--el-text-color-primary, #303133);
        margin-bottom: 16px;
        padding-bottom: 8px;
        border-bottom: 2px solid var(--el-border-color-light, #ebeef5);
      }
      
      .catalog-list {
        .catalog-item {
          cursor: pointer;
          padding: 8px 12px;
          margin: 4px 0;
          border-radius: 6px;
          transition: all 0.3s ease;
          font-size: 14px;
          color: var(--el-text-color-regular, #606266);
          
          &:hover {
            background-color: var(--el-fill-color-light, #f5f7fa);
            color: var(--el-color-primary, #409eff);
          }
          
          &.level-1 {
            font-weight: 600;
            font-size: 15px;
            padding-left: 12px;
          }
          
          &.level-2 {
            font-weight: 500;
            font-size: 14px;
            padding-left: 24px;
          }
          
          &.level-3 {
            font-weight: 400;
            font-size: 13px;
            padding-left: 36px;
          }
          
          &.level-4, &.level-5, &.level-6 {
            font-weight: 400;
            font-size: 12px;
            padding-left: 48px;
            color: var(--el-text-color-placeholder, #c0c4cc);
          }
        }
      }
    }
  }
  
  .empty-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 60px 20px;
    color: var(--el-text-color-placeholder, #c0c4cc);
    
    .empty-icon {
      font-size: 48px;
      margin-bottom: 16px;
      opacity: 0.6;
    }
    
    .empty-text {
      font-size: 14px;
      font-weight: 500;
    }
  }
}

// 响应式设计
@media (max-width: 1024px) {
  .markdown-renderer {
    .content-area {
      flex-direction: column;
      gap: 16px;
      
      .catalog {
        width: 100%;
        position: static;
        max-height: none;
        order: -1; // 目录显示在内容前面
        
        .catalog-list {
          display: flex;
          flex-wrap: wrap;
          gap: 8px;
          
          .catalog-item {
            flex: 0 0 auto;
            white-space: nowrap;
            margin: 0;
            
            &.level-1, &.level-2, &.level-3, &.level-4, &.level-5, &.level-6 {
              padding-left: 12px;
            }
          }
        }
      }
      
      .markdown-content {
        .image-container {
          .markdown-image {
            max-height: 350px !important; // 平板端适中的图片高度
          }
        }
        
        // 平板端全局图片约束
        img {
          max-height: 350px !important;
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .markdown-renderer {
    .content-area {
      .markdown-content {
        // 移动端全局图片约束
        img {
          max-height: 300px !important;
        }
        
        h1 {
          font-size: 24px;
        }
        
        h2 {
          font-size: 20px;
        }
        
        h3 {
          font-size: 18px; // 保持比正文大但比二级标题小
        }
        
        .image-container {
          margin: 16px 0;
          
          .markdown-image {
            border-radius: 6px;
            max-height: 300px !important; // 移动端稍微减小图片高度
          }
        }
      }
      
      .catalog {
        .catalog-list {
          .catalog-item {
            font-size: 13px;
            padding: 6px 10px;
          }
        }
      }
    }
  }
}

// 深色模式支持
@media (prefers-color-scheme: dark) {
  .markdown-renderer {
    .content-area {
      .markdown-content {
        color: var(--el-text-color-primary, #e5eaf3);
        
        h1, h2, h3, h4, h5, h6 {
          color: var(--el-text-color-primary, #e5eaf3);
        }
        
        p {
          color: var(--el-text-color-regular, #a3a6ad);
        }
      }
      
      .catalog {
        .catalog-title {
          color: var(--el-text-color-primary, #e5eaf3);
          border-bottom-color: var(--el-border-color-light, #4c4d4f);
        }
        
        .catalog-list {
          .catalog-item {
            color: var(--el-text-color-regular, #a3a6ad);
            
            &:hover {
              background-color: var(--el-fill-color-darker, #2b2b2b);
              color: var(--el-color-primary, #409eff);
            }
            
            &.level-4, &.level-5, &.level-6 {
              color: var(--el-text-color-placeholder, #6b6b6b);
            }
          }
        }
      }
    }
  }
}

// 最强图片约束 - 覆盖所有可能的样式冲突
.markdown-renderer img,
.markdown-renderer .markdown-image,
.markdown-renderer .image-container img {
  max-width: 100% !important;
  max-height: 400px !important;
  width: auto !important;
  height: auto !important;
  object-fit: cover !important;
  box-sizing: border-box !important;
}

// 移动端图片约束
@media (max-width: 768px) {
  .markdown-renderer img,
  .markdown-renderer .markdown-image,
  .markdown-renderer .image-container img {
    max-height: 300px !important;
  }
}

// 平板端图片约束
@media (max-width: 1024px) {
  .markdown-renderer img,
  .markdown-renderer .markdown-image,
  .markdown-renderer .image-container img {
    max-height: 350px !important;
  }
}
</style>
